﻿using MixingStation.LTWebService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MixingStation
{
    public partial class LocalUserCfgForm : Form
    {
        private DataTable m_BindDT = null;
        public LocalUserCfgForm()
        {
            InitializeComponent();
        }

        private void LocalUserCfgForm_Load(object sender, EventArgs e)
        {
            InitDT();
            Refresh();
        }

        private void InitDT()
        {
            m_BindDT = new DataTable();
            m_BindDT.Columns.Add("Id");
            m_BindDT.Columns.Add("UserName");
            m_BindDT.Columns.Add("EmployeeName");
            m_BindDT.Columns.Add("Password");
            m_BindDT.Columns.Add("IsAdmin");
        }

        private void Refresh()
        {
            m_BindDT.Rows.Clear();
            dataGridView.DataSource = m_BindDT;

            string sql = "select * from [User]";
            try
            {
                DataTable dt = CommonHelper.DoSelectOpreation(sql);
                if (dt == null || dt.Rows.Count == 0)
                    return;
                foreach (DataRow dr in dt.Rows)
                    m_BindDT.Rows.Add(dr["Id"], dr["UserName"].ToString(), dr["EmployeeName"].ToString(),
                        dr["Password"].ToString(), Convert.ToBoolean(dr["IsAdmin"]));
                dataGridView.DataSource = m_BindDT;
            }
            catch (Exception ex)
            {
                string str = "刷新用户列表失败：" + ex.Message;
                LogHelper.error(str);
                MessageBox.Show(str);
            }
        }

        private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 3)
            {
                if (e.Value != null && e.Value.ToString().Length > 0)
                {
                    e.Value = new string('*', e.Value.ToString().Length);
                }
            }
        }

        private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
              TextBox t = e.Control as TextBox;
              if (t != null)
              {
                  if (this.dataGridView.CurrentCell.ColumnIndex == 2)
                      t.PasswordChar = '*';
                  else
                      t.PasswordChar = new char();
              }
        }

        //同步
        private void btnSynchronize_Click(object sender, EventArgs e)
        {
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                bool isOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);
                if (!isOnline)
                {
                    MessageBox.Show("离线状态下无法同步数据！");
                    return;
                }
                AdminConfirmForm form = new AdminConfirmForm();
                form.UserType = "管理员";
                form.IsOnline = isOnline;
                form.Title = "同步";
                if (DialogResult.OK == form.ShowDialog())
                {
                    if (!SynchronizeHelper.SynchronizeUser(form.User))
                    {
                        MessageBox.Show("同步用户信息异常，详细信息请参考日志文件");
                        return;
                    }
                    MessageBox.Show("同步用户信息成功！");
                    Refresh();
                }
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                bool isOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);
                AdminConfirmForm form = new AdminConfirmForm();
                form.UserType = "管理员";
                form.IsOnline = isOnline;
                form.Title = "分配权限";
                if (DialogResult.OK == form.ShowDialog())
                {
                    List<string> sqlList = new List<string>();
                    foreach (long id in m_ModifyInfo.Keys)
                    {
                        string sql = "update [User] set IsAdmin = " + m_ModifyInfo[id] + " where Id = '" + id.ToString() + "'";
                        sqlList.Add(sql);
                    }
                    if (sqlList.Count == 0)
                    {
                        MessageBox.Show("未有修改权限的数据!");
                        return;
                    }
                    try
                    {
                        if (!CommonHelper.InsertDataByBatch(sqlList.ToArray()))
                        {
                            MessageBox.Show("批量分配管理员权限错误，详细信息请参考日志文件！");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.error("批量分配管理员权限异常:" + ex.ToString());
                        MessageBox.Show("批量分配管理员权限异常,详细信息请参考日志文件!");
                        return;
                    }
                    MessageBox.Show("批量分配管理员权限成功！");
                    Refresh();
                }
            }
        }

        private Dictionary<long, bool> m_ModifyInfo = new Dictionary<long,bool> ();
        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            if (e.ColumnIndex == 4)//当单击复选框
            {
                long id = Convert.ToInt64( dataGridView.Rows[e.RowIndex].Cells["IdColumn"].Value.ToString());
                if (Convert.ToString(dataGridView.Rows[e.RowIndex].Cells["IsAdminColumn"].Value) == "true")
                {
                    if ((dataGridView.Rows[e.RowIndex].Cells["UserColumn"].Value).ToString().ToUpper() == "SYSTEM")
                    {
                        MessageBox.Show("系统管理员不能去掉管理员权限!");
                        return;
                    }
                    dataGridView.Rows[e.RowIndex].Cells["IsAdminColumn"].Value = "false";

         
                    if(m_ModifyInfo.ContainsKey(id))
                        m_ModifyInfo[id] = false;
                    else
                        m_ModifyInfo.Add(id, false);
                }
                else
                {
                    dataGridView.Rows[e.RowIndex].Cells["IsAdminColumn"].Value = "true";
                      if(m_ModifyInfo.ContainsKey(id))
                        m_ModifyInfo[id] = true;
                    else
                        m_ModifyInfo.Add(id, true);
                }
            }
        }
    }
}
